// 提供一个用于读取、写入本地存储数据的工具库

const STORAGE_NAME = 'snackshop'// 整个仓库在本地存储的名字
const STORAGE_TYPE = 'localStorage' // 设置仓库存储的类型

const getAllData = () => {
  let storageData = window[STORAGE_TYPE].getItem(STORAGE_NAME)
  // 判断获取的数据,如果为null，需要写入一些初始的数据(如果有数据则进行json解析)
  storageData = storageData ? JSON.parse(storageData) : {}
  return storageData
}

const saveStorage = (key, data) => {
  console.log('保存数据', key, data)
  let storageData = getAllData()
  // console.log(storageData)
  // 存储完整的数据
  storageData[key] = data
  // 直接存储新数据
  window[STORAGE_TYPE].setItem(STORAGE_NAME, JSON.stringify(storageData))
}

const getStorage = (key) => {
  let storageData = getAllData()
  if (storageData.hasOwnProperty(key)) {
    return storageData[key]
  }
  return null
}

const removeStorage = (key) => {
  let storageData = getAllData()
  if (storageData.hasOwnProperty(key)) {
    storageData[key] = null
    // 直接存储新数据
    window[STORAGE_TYPE].setItem(STORAGE_NAME, JSON.stringify(storageData))
  }
}

export default{
  save: saveStorage,
  get: getStorage,
  remove: removeStorage
}
